#include "materialaccess.h"
#include "ui_materialaccess.h"
#include "util/database/databasemanager.h"
#include <QRandomGenerator>
#include <QMessageBox>
#include <QDateTime>
#include <QTimer>
#include <QDebug>

MaterialAccess::MaterialAccess(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MaterialAccess),
    m_materialTableWidget(nullptr),
    m_materialTreeWidget(nullptr),
    m_materialService(new MaterialService())
{
    ui->setupUi(this);
    initUI();
    initConnections();

    // 延迟加载数据，避免UI卡顿
    QTimer::singleShot(100, this, &MaterialAccess::loadMaterialData);
}

MaterialAccess::~MaterialAccess()
{
    delete m_materialService;
    delete ui;
}

void MaterialAccess::initUI()
{
    // 初始化树形视图
    m_materialTreeWidget = new StyledTreeView(this);
    ui->materialTreeLayout->addWidget(m_materialTreeWidget);
    QStringList treeHeaders = {"name", "count"};
    m_materialTreeWidget->setHeaderLabels(treeHeaders);
    m_materialTreeWidget->setTreeData(generateTreeData());

    // 初始化表格视图
    m_materialTableWidget = new StyledTableView(this);
    ui->materialTableLayout->addWidget(m_materialTableWidget);

    // 定义表头：字段显示顺序 + 字段->标题映射
    QList<QString> fieldOrder = {"id", "name", "model", "quantity", "lastUpdated"};
    QMap<QString, QString> headerMap;
    headerMap["id"] = "物料ID";
    headerMap["name"] = "名称";
    headerMap["model"] = "型号";
    headerMap["quantity"] = "库存";
    headerMap["lastUpdated"] = "最后操作时间";

    // 设置表格表头
    m_materialTableWidget->setHeaders(fieldOrder, headerMap);
}

void MaterialAccess::initConnections()
{
    connect(m_materialTreeWidget, &StyledTreeView::nodeClicked,
            this, &MaterialAccess::onTreeNodeClicked);

    connect(m_materialTableWidget, &StyledTableView::actionButtonClicked,
            this, &MaterialAccess::onTableButtonClicked);
}

void MaterialAccess::loadMaterialData()
{
    m_materialDataList.clear();

    // 从数据库加载物料数据
    QString errorMsg;
    // 变更：获取QList<QMap<QString, QVariant>>类型数据
    QList<MaterialVO*> materialList = m_materialService->getMaterialsByCondition(MaterialVO(), &errorMsg);

    if (!errorMsg.isEmpty()) {
        QMessageBox::warning(this, "数据加载失败",
                             QString("无法加载物料数据: %1").arg(errorMsg));
        return;
    }

    m_materialDataList = materialList;
    m_materialTableWidget->setDataList(m_materialDataList);
}


QList<QMap<QString, QString>> MaterialAccess::generateTreeData()
{
    QList<QMap<QString, QString>> data;

    data << QMap<QString, QString>{{"id", "1"}, {"name", "电子元件"}, {"parentId", "0"}, {"count", "100"}}
    << QMap<QString, QString>{{"id", "2"}, {"name", "机械零件"}, {"parentId", "0"}, {"count", "80"}}
    << QMap<QString, QString>{{"id", "1-1"}, {"name", "电阻"}, {"parentId", "1"}, {"count", "50"}}
    << QMap<QString, QString>{{"id", "1-2"}, {"name", "电容"}, {"parentId", "1"}, {"count", "30"}}
    << QMap<QString, QString>{{"id", "1-1-A"}, {"name", "金属膜电阻"}, {"parentId", "1-1"}, {"count", "20"}};

    return data;
}

void MaterialAccess::onTableButtonClicked(const QString& operation, int inventory_id, int oper_num, int row)
{
    if (row < 0 || row >= m_materialDataList.size()) {
        QMessageBox::warning(this, "错误", "无效的物料行索引");
        return;
    }

    // 变更：从QMap中获取数据
    MaterialVO* materialVO = m_materialDataList[row];
    if (materialVO->get_inventory_id() != inventory_id) {
        QMessageBox::warning(this, "错误", "物料信息不匹配");
        return;
    }

    int oldQuantity = materialVO->get_inventory_id();
    QString errorMsg;
    bool success = false;
    QString successMsg, errorDetail;

    if (operation == "save") {
        materialVO->set_inventory_quantity(oldQuantity + oper_num);
        materialVO->set_update_time(QDateTime::currentDateTime());

        //调用数据库信息
        success = m_materialService->saveMaterial(materialVO, oper_num, &errorMsg);

        successMsg = QString("物料: %1\n存入成功\n新库存: %2")
                .arg(materialVO->get_material_name()).arg(materialVO->get_inventory_quantity());
        errorDetail = QString("存入失败: %1").arg(errorMsg);
    }
    else if (operation == "take") {
        if (oper_num > oldQuantity) {
            QMessageBox::warning(this, "库存不足",
                                 QString("物料: %1\n当前库存: %2\n请求取出: %3\n库存不足!")
                                 .arg(materialVO->get_material_name()).arg(oldQuantity).arg(oper_num));
            return;
        }

        materialVO->set_inventory_quantity(oldQuantity - oper_num);
        materialVO->set_update_time(QDateTime::currentDateTime());

        success = m_materialService->saveMaterial(materialVO, oper_num*(-1), &errorMsg);

        successMsg = QString("物料: %1\n取出成功\n新库存: %2")
                .arg(materialVO->get_material_name()).arg(materialVO->get_inventory_quantity());
        errorDetail = QString("取出失败: %1").arg(errorMsg);
    }

    showOperationMessage(success, successMsg, errorDetail);

    if (success) {
        m_materialTableWidget->updateTableFromEntities();

        m_materialTableWidget->refreshTableView();
    }
}

void MaterialAccess::onTreeNodeClicked(const QString& nodeId, const QMap<QString, QString>& nodeData)
{
    QString nodeName = nodeData.value("name", "未知节点");
    QString nodeCount = nodeData.value("count", "0");

    QMessageBox::information(this, "节点选中",
                             QString("选中节点: %1\nID: %2\n数量: %3")
                             .arg(nodeName).arg(nodeId).arg(nodeCount));
}

void MaterialAccess::refreshMaterialData()
{
    loadMaterialData();
    QMessageBox::information(this, "刷新成功", "物料数据已更新");
}

void MaterialAccess::showOperationMessage(bool success, const QString& successMsg, const QString& errorMsg)
{
    if (success) {
        QMessageBox::information(this, "操作成功", successMsg);
    } else {
        QMessageBox::critical(this, "操作失败", errorMsg);
    }
}
